<template>
  <ActionTable :showBack="false" @addRow="showModal('ADD', { state: 0 })">
    <div class="screen-box">
      <a-form ref="screenFormRef" layout="inline" :model="screenData">
        <a-form-item name="productName">
          <a-input v-model:value="screenData.productName" placeholder="商品名称" />
        </a-form-item>
        <a-form-item name="ticketType">
          <a-select
            allowClear
            v-model:value="screenData.ticketType"
            placeholder="归属类别"
            style="width: 120px"
          >
            <template v-for="menuItem in menuOfData">
              <a-select-option :value="menuItem.id">{{
                menuItem.menuName
              }}</a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item name="state">
          <a-select
            allowClear
            v-model:value="screenData.state"
            placeholder="商品状态"
            style="width: 120px"
          >
            <a-select-option :value="1">开启</a-select-option>
            <a-select-option :value="0">关闭</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="screenHandleSubmit">搜索</a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="resetScreenForm">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
  </ActionTable>
  <a-table
    :columns="columns"
    :row-key="(record) => record.id"
    :data-source="productOfData"
    :pagination="state.pagination"
    :loading="state.loading"
    @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'ticketType'">
        {{ ticketTypeToName(record.ticketType) }}
      </template>
      <template v-if="column.key === 'state'">
        <a-switch
          :checked="record.state === 1"
          checked-children="开启"
          un-checked-children="关闭"
          @click="(checked) => showMenu(checked, record)"
        />
      </template>
      <template v-if="column.key === 'action'">
        <TableRowAction
          :showSelect="false"
          @updateItem="showModal('UPDATE', record)"
          @deleteItem="delRow(record.id)"
        />
      </template>
    </template>
  </a-table>
  <contextHolder />
</template>
<script lang="ts" setup>
import { TableProps, message as $message, Modal } from "ant-design-vue";
import { h, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { paginationToQuery, proxyFilterEmptyValues } from "@/utils/common";
import { modalTitleEnum } from "@/enums/modalEnum";
import {
  insertTicketProduct,
  selectAllProduct,
  selectProductByExample,
  updateTicketProduct,
} from "@/api/system/product";
import ProductItemSchemas from "./productItemSchemas.vue";
import { deleteTicketProduct } from "@/api/ticket/product";
import { selectAllMenu } from "@/api/ticket/menu";
const route = useRoute();
const [modal, contextHolder] = Modal.useModal();
const childRef = ref();
const screenFormRef = ref();
const columns = [
  {
    dataIndex: "id",
    title: "ID",
    key: "id",
    align: "center",
  },
  {
    dataIndex: "ticketType",
    title: "归属类别",
    key: "ticketType",
    align: "center",
  },
  {
    dataIndex: "productName",
    title: "商品名称",
    key: "productName",
    align: "center",
  },
  {
    dataIndex: "maxPoint",
    title: "最大分值(积分/学分)",
    key: "maxPoint",
    align: "center",
  },
  {
    dataIndex: "state",
    title: "状态",
    key: "state",
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    align: "center",
  },
];

const screenData = reactive<API.ProductItem>({
  ticketType: null,
  productName: "",
  state: null,
});

const menuOfData = ref<API.TicketMenu[]>([]);
const productOfData = ref<API.ProductItem[]>([]);

const state = reactive({
  loading: true,
  pagination: {
    pageSize: 10,
    current: 1,
    total: 0,
    showTotal: (total) => `总${total}条`,
  },
});

watch(
  () => route.query.type,
  (newVal, oldVal) => {
    if (newVal === oldVal) return;
    loadData();
  }
);

/**
 * 获取数据
 */
const loadData = async () => {
  state.loading = true;
  const { seachList, seachTotal } = await selectAllProduct(
    paginationToQuery(state.pagination)
  );
  productOfData.value = seachList;
  state.pagination.total = seachTotal;
  const menuValues = await selectAllMenu({ pageNum: 1, pageSize: 999 });
  menuOfData.value = menuValues.seachList.filter(
    (item) => item.state === 0 || item.state === 1
  );
  state.loading = false;
};

/**
 * 商品关联类别Id转Name
 * @param ticketType
 */
const ticketTypeToName = (ticketType: number) => {
  const menuItem = menuOfData.value.find((menuItem) => menuItem.id === ticketType);
  return menuItem?.menuName;
};

/**
 * 分页切换
 * @param page
 */
const handleTableChange: TableProps["onChange"] = (page) => {
  state.pagination.current = page.current!;
  loadData();
};

/**
 * 查看二级类别
 */
// const subMenu = (menu) => {
//   router.push({ name: 'ticket-menu-item', query: { menuId: menu.id } });
// }

/**
 * 显示模态框
 * @param type
 * @param data
 */
const showModal = (type: string, data?: any) => {
  const menuForm = () =>
    h(ProductItemSchemas, {
      ref: childRef,
      formData: data,
      menuOfData: menuOfData.value,
    });
  modal.confirm({
    title: modalTitleEnum[type] + "商品",
    icon: null,
    width: 1000,
    content: menuForm,
    okText: "提交",
    cancelText: "取消",
    async onOk() {
      const params: API.ProductItem = childRef.value.formState;
      if (type === "ADD") {
        const { msg } = await insertTicketProduct(params);
        msg === "success" ? loadData() : $message.error(msg);
      } else if (type === "UPDATE") {
        const { msg } = await updateTicketProduct(params);
        msg === "success" ? loadData() : $message.error(msg);
      }
    },
    onCancel() {
      Modal.destroyAll();
    },
  });
};

/**
 * 删除商品
 */
const delRow = async (id) => {
  const { msg } = await deleteTicketProduct({ id });
  msg === "success" ? $message.success("删除成功") : $message.error(msg);
  loadData();
};

const showMenu = async (checked, ProductItem) => {
  const { msg } = await updateTicketProduct({
    id: ProductItem.id,
    state: checked ? 1 : 0,
  });
  msg === "success"
    ? (ProductItem.state = Math.abs(ProductItem.state - 1))
    : $message.error(msg);
  checked ? (ProductItem.state = 1) : (ProductItem.state = 0);
};

/**
 * 筛选
 */
const screenHandleSubmit = async () => {
  state.loading = true;
  const { seachList, seachTotal } = await selectProductByExample(
    proxyFilterEmptyValues(screenData),
    { pageNum: 1, pageSize: 999 }
  );
  productOfData.value = seachList;
  state.pagination.total = seachTotal;
  state.loading = false;
};

/**
 * 重置筛选表单
 */
const resetScreenForm = () => {
  screenFormRef.value.resetFields();
};

onMounted(() => {
  loadData();
});
</script>
